<?php
/**
 * 封装 DsCache, 单件模式 更易操作;
 * @filesource _cache.class.php
 * @package peck
 * @subpackage _cache
 * @version $id: 2.0, utf8, Sat Dec  5 14:10:38 CST 2009
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2009 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example
 *   
 *   //文件缓存
 *   $GLOBALS['DsCache'] = array(
 *   	'cache_dir' => '/tmp', //缓存目录(必须)
 *   	'life_time' => 900, //全局缓存时间 900s.
 *   	);
 *   
 *   //内存缓存
 *   $GLOBALS['DsCache'] = array(
 *   	'cache_type' => 'phpmencached' //缓存类型(必须)
 *   	'servers' => array(		//缓存服务器,至少填一个(必需)
 *   			array( 'host' => '127.0.0.1', 'port' => '11211', 'weight' => 99, ),
 *   			array( 'host' => '192.168.1.112', 'port' => '11211', 'weight' => 32, ),	
 *   			), 
 *   	'life_time' => 900, //全局缓存时间 900s.
 *   	'persistent' => true, //持久连接
 *   	'compressed' => false, //压缩数据与否
 *   	'encoding_key' => false, //加密缓存ID, 即 MD5($key)
 *   	);
 *   
 *   //约定: 如果 'life_time' 设置为 0 表示不检查缓存有效期(即缓存永久有效).
 *
 *	 $cache = _cache::object();
 *   $cache->set('select * from test', $data); //缓存变量
 *   $cache->get('cache id 1234'); //得到缓存
 *   $cache->remove('my cache file'); //清除特定缓存文件
 *   $cache->clean(); //清空缓存目录
 */
require_once 'spl_autoload.func.php';
class _cache{
    private static $instance;
    
    /**
     * 缓存对象
     * @var object
     */
    private $_cache;

    /**
     * 构造,析构函数
     */
    private function __construct(){}
    private function __clone(){}

    /**
     * 获得缓存静态对像
     */
    private static function instance(array $default_policy = null){
        if( !(self::$instance instanceof self) ){
        	//$policy = _core::object()->get('cache');
            $policy = $GLOBALS['DsCache'];
        	if ( empty($policy) ) {
        		throw new LogicException('('.__METHOD__.')Error: Someone should give any stuff for DsCache !');
        	}
			
        	$cache_type = empty($policy['cache_type']) ? 'serialfile' : $policy['cache_type'];
            self::$instance = new self();
            
            try{
            	self::$instance->_cache = new $cache_type($policy);
            }catch(Exception $e){
                throw new LogicException('('.__METHOD__.')Error: Start Cache('.$cache_type.') Failed ! '.$e->__toString());
            }
        }
        return self::$instance;
    }
	public static function object(){
		return self::instance()->_cache;
	}
    
}//END class Cache
?>
